package repository

import (
	"gitee.com/apinktara/cart/domain/model"
	"github.com/jinzhu/gorm"
)

type ICartRepository interface {
	InitTable() error
	FindCartByID(int64) (*model.Cart, error)
	CreateCart(*model.Cart) (int64, error)
	DeleteCartByID(int64) error
	UpdateCart(*model.Cart) error
	FindAll(int64) ([]model.Cart, error)

	CleanCart(int64) error
	IncrNum(int64, int64) error
	DecrNum(int64, int64) error
}

func NewCartRepository(db *gorm.DB) ICartRepository {
	return &CartRepository{mysqlDB: db}
}

type CartRepository struct {
	mysqlDB *gorm.DB
}

func (u *CartRepository) InitTable() error {
	return u.mysqlDB.CreateTable(model.Cart{}).Error
}

func (u *CartRepository) FindCartByID(CartID int64) (Cart *model.Cart, err error) {
	Cart = &model.Cart{}
	return Cart, u.mysqlDB.First(Cart, CartID).Error
}

func (u *CartRepository) CreateCart(cart *model.Cart) (int64, error) {
	db := u.mysqlDB.FirstOrCreate(cart, model.Cart{
		ProductID: cart.ProductID,
		SizeID:    cart.SizeID,
		UserID:    cart.UserID,
	})
	if db.Error != nil {
		return 0, db.Error
	}
	if db.RowsAffected == 0 {
		return 0, nil
	}
	return cart.ID, nil
}

func (u *CartRepository) DeleteCartByID(cartID int64) error {
	return u.mysqlDB.Where("id =?", cartID).Delete(&model.Cart{}).Error
}

func (u *CartRepository) UpdateCart(Cart *model.Cart) error {
	return u.mysqlDB.Model(Cart).Update(Cart).Error
}

func (u *CartRepository) FindAll(userID int64) (CartAll []model.Cart, err error) {
	return CartAll, u.mysqlDB.Where("user_id = ?", userID).Find(&CartAll).Error
}

func (u *CartRepository) CleanCart(userID int64) error {
	return u.mysqlDB.Where("user_id = ?", userID).Delete(&model.Cart{}).Error
}

func (u *CartRepository) IncrNum(cartID int64, num int64) error {
	cart:=&model.Cart{
		ID: cartID,
	}
	return u.mysqlDB.Model(cart).UpdateColumn("num",gorm.Expr("num + ?",num)).Error
}

func (u *CartRepository)DecrNum(cartID int64, num int64)error  {
	cart:=&model.Cart{
		ID: cartID,
	}
	db:= u.mysqlDB.Model(cart).Where("num >= ?" ,num).UpdateColumn("num",gorm.Expr("num - ?",num))
	if db.Error!=nil {
		return db.Error
	}
	if db.RowsAffected == 0 {
		return nil
	}
	return nil
}
